package com.jxkj.interceptor;

import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import com.jxkj.constant.CartConstant;
import com.jxkj.vo.UserInfoVO;
import com.jxkj.vo.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 项目: shop-car
 * <p>
 * 功能描述: 拦截器
 *
 * @author: WuChengXing
 * @create: 2020-08-03 23:52
 **/
@Component
public class CartInterceptor implements HandlerInterceptor {

    /**
     * 线程共享类，因为在tomcat容器中，请求默认是串行执行的，所有之后的请求可以从threadlocal中获取信息
     */
    public static ThreadLocal<UserInfoVO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoVO userInfoVO = new UserInfoVO();
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("xxx");
        if (userVO != null) {
            userInfoVO.setUserId(userVO.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (CartConstant.COOKIE_USER_KEY_NAME.equals(cookieName)) {
                    userInfoVO.setUserKey(cookie.getValue());
                }
            }
        }

        if (StringUtils.isEmpty(userInfoVO.getUserKey())) {
            String userKey = UUID.randomUUID().toString();
            userInfoVO.setUserKey(userKey);
        }
        threadLocal.set(userInfoVO);
        /*// 不管cookie里面有没有值，都会重新插入一遍
        Cookie cookie = new Cookie(CartConstant.COOKIE_USER_KEY_NAME, userInfoVO.getUserKey());
        response.addCookie(cookie);*/
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoVO userInfoVO = threadLocal.get();
        // 如果不是临时用户就往cookie中保存
        if (!StringUtils.isEmpty(userInfoVO.getUserKey())) {
            Cookie cookie = new Cookie(CartConstant.COOKIE_USER_KEY_NAME, userInfoVO.getUserKey());
            cookie.setDomain("localhost");
            cookie.setMaxAge(CartConstant.COOKIE_TEMP_USER_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
